import { _decorator } from "cc";
import { Singleton } from "../decorators/Singleton";
const { ccclass } = _decorator;

type DataValue = string | number | boolean | object | Array<any>;

@Singleton
@ccclass("DataManager")
export class DataManager {
  private _dataMap: Map<string, DataValue> = new Map();

  constructor() {
    // 初始化默认数据
  }

  public setData(key: string, value: DataValue): void {
    this._dataMap.set(key, value);
  }

  public getData<T extends DataValue>(key: string, defaultValue?: T): T {
    if (!this._dataMap.has(key) && defaultValue !== undefined) {
      this.setData(key, defaultValue);
      return defaultValue;
    }
    return this._dataMap.get(key) as T;
  }

  public hasData(key: string): boolean {
    return this._dataMap.has(key);
  }

  public deleteData(key: string): void {
    this._dataMap.delete(key);
  }

  public clearAll(): void {
    this._dataMap.clear();
  }

  public saveToLocal(): void {
    const data = {};
    this._dataMap.forEach((value, key) => {
      data[key] = value;
    });
    localStorage.setItem("gameData", JSON.stringify(data));
  }

  public loadFromLocal(): void {
    const dataStr = localStorage.getItem("gameData");
    if (dataStr) {
      const data = JSON.parse(dataStr);
      Object.keys(data).forEach((key) => {
        this.setData(key, data[key]);
      });
    }
  }
}
